package projorientado.image;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.util.Vector;

public class ImageUtil {

    public static ImageLayerData fullEdgeDetector(BufferedImage source) {

        float verticalMatrix[] = {
            -1, 0, 1,
            -2, 0, 2,
            -1, 0, 1
        ,
           };
        float horizontalMatrix[] = {
            -1, -2, -1,
            0, 0, 0,
            1, 2, 1
        };

        ImageLayerData ret, iaux;

        BufferedImage baux = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB);

        new ConvolveOp(new Kernel(3, 3, verticalMatrix), ConvolveOp.EDGE_NO_OP, null).filter(source, baux);

        ret = ImageLayerData.extractBrightnessLayer(baux);

        new ConvolveOp(new Kernel(3, 3, horizontalMatrix), ConvolveOp.EDGE_NO_OP, null).filter(source, baux);

        iaux = ImageLayerData.extractBrightnessLayer(baux);

        int w = source.getWidth();
        int h = source.getHeight();

        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                float sum = 0.0f;
                sum += ret.getPixel(x, y);
                sum += iaux.getPixel(x, y);
                ret.setPixel(x, y, Math.max(sum, 1f));
            }
        }

        return ret;
    }
    
    public static void filterColor(BufferedImage image, Vector<Color> usedColors, double maxDistance, boolean fixColor, Color fillColor) {
        int w = image.getWidth(), h = image.getHeight();
        for(int x = 0; x < w; x++) {
            for(int y = 0; y < h; y++) {
                int point = image.getRGB(x, y);
                boolean found = false;
                for(int i = 0; i < usedColors.size(); i++) {
                    Color uc = usedColors.elementAt(i);
                    Color pc = new Color(point);
                    double dist = colorDistance(uc,pc);
                    if(dist < maxDistance) {
                        if(fixColor) {
                            image.setRGB(x, y, uc.getRGB());
                        }
                        found = true;
                        break;
                    }
                }
                if(!found)
                    image.setRGB(x, y, fillColor.getRGB());
            }
        }
    }
    
    public static double colorDistance(Color c1, Color c2) {
        int r = c1.getRed()-c2.getRed();
        int g = c1.getGreen()-c2.getGreen();
        int b = c1.getBlue()-c2.getBlue();
        return Math.sqrt(r*r + g*g + b*b);
    }
}
